package org.xm.sk.filter.auth;

import java.io.IOException;
import java.io.Serializable;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;
import org.xm.sk.controller.AppErrorController;

@Service
public class UserAuthEntryPoint
        implements AuthenticationEntryPoint, Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 6652191256536561048L;

    @Autowired
    private MessageSource messages;

    @Override
    public void commence(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION,
                new Exception(messages.getMessage("session.msg.invalid_session",
                        null, "Unauthorized", null)));
        response.setStatus(401);
        request.getRequestDispatcher(AppErrorController.ERROR_PATH)
                .forward(request, response);
    }

}
